from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponse
from django.shortcuts import render, redirect

# Create your views here.
from django.views import View
from django_redis import get_redis_connection
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from users.models import User
from users.serializsers import UserSerializer
class IndexViews(View):
    def get(self, request):
        return render(request, 'index.html')


class RegisterIndexView(View):
    def get(self, request):
        return render(request, 'register.html')


class RegisterView(CreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    def create(self, request, *args, **kwargs):
        data = request.data
        phonecode = data.get('phonecode')
        mobile = data.get('mobile')
        password = data.get('password')

        redis_conn = get_redis_connection('verify_code')
        redis_sms_code = redis_conn.get(mobile)
        if not redis_sms_code:
            return Response({'errno':9999,'errmsg':'验证码过期'})
        if redis_sms_code.decode() != phonecode:
            return Response({'errno':9999,'errmsg':'短信验证码错误'})

        user_info = {
            'mobile':mobile,
            'password':password,
            'username':mobile
        }
        serializer = self.get_serializer(data=user_info)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({
            "errno": "0",
            "errmsg": "注册成功"
        })

class LoginView(APIView):
    def get(self,request):
        return render(request,'login.html')

    def post(self,request):
        data = request.data
        mobile = data.get('mobile')
        password = data.get('password')
        if not all([mobile,password]):
            return Response({'errmsg':'参数不全','errno':9999})
        user = authenticate(request, username=mobile, password=password)
        if user:
            login(request,user)
        else:
            return Response({'errmsg':'密码错误','errno':9999})

        response = Response({'errno':0,'errmsg':'登陆成功'})
        # 按照默认配置,保存两周
        request.session.set_expiry(None)
        response.set_cookie('username', user.mobile, expires=3600 * 24 * 7)
        # 4.返回响应
        return response
